package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmLoginDto;
import com.heima.model.wemedia.pojo.WmUser;
import com.heima.utils.common.AppJwtUtil;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description: test
 * @Create by: JJ菜菜
 * @Date: 2022/1/6 21:34
 */
@Service
public class WmUserServiceImpl extends ServiceImpl<WmUserMapper, WmUser> implements WmUserService {

    @Autowired
    private WmUserMapper wmUserMapper;

    @Override
    public ResponseResult login(WmLoginDto wmLoginDto) {

        String name = wmLoginDto.getName();
        String password = wmLoginDto.getPassword();
        // 检查参数是否存在
        if (StringUtils.isEmpty(name) || StringUtils.isEmpty(password)){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "用户名或者密码为错");
        }
        // 根据用户明查询用户是否存在
        LambdaQueryWrapper<WmUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmUser::getName, name);
        WmUser wmUser = wmUserMapper.selectOne(queryWrapper);
        if (wmUser == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        // 查询到了之后，比较密码, 将输入的密码加盐后进行md5
        String md5Password = DigestUtils.md5DigestAsHex((password + wmUser.getSalt()).getBytes());
        if (!md5Password.equals(wmUser.getPassword())){
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }

        // 验证通过之后， 颁发token令牌
        String token = AppJwtUtil.getToken(wmUser.getId().longValue());
        // 将token和对象返回
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("user", wmUser);
        return ResponseResult.okResult(map);
    }
}
